package btree;



import diskmgr.*;
import global.*;

public class BTreeFile {

	private BTHeaderPage header;
	private PageId headerID;
	
	public BTHeaderPage getHeaderPage()
	{
		return header;
	}
	
	public BTreeFile(String fileName) throws FileEntryNotFoundException
	{
		try {
			PageId pageno=SystemDefs.JavabaseDB.get_file_entry(fileName);
			if(pageno==null)
			{
				throw new FileEntryNotFoundException(null, "btree.BTreeFile(String fileName): file entry not found");
			}
			else 
			{
				headerID=pageno;
				header=new BTHeaderPage(headerID);
			}
		} catch (Exception e) {
			throw new FileEntryNotFoundException(e, "btree.BTreeFile(String fileName): file entry not found");
		}
	}
	
	public BTreeFile(String filename,
            int keytype,
            int keysize,
            int delete_fashion)
	{
		try {
			PageId pageno=SystemDefs.JavabaseDB.get_file_entry(filename);
			if(pageno==null)
			{
				try {
					header=new BTHeaderPage();
					headerID=header.getCurPage();
					// add the new file entry
					SystemDefs.JavabaseDB.add_file_entry(filename, headerID);
					header.set_keyType((short)keytype);
					header.set_deleteFashion(delete_fashion);
					header.set_maxKeySize(keysize);
					header.set_rootId(new BTLeafPage(keytype).getCurPage());
				} catch (Exception e) {

					e.printStackTrace();
				}
			}
			else 
			{
				headerID=pageno;
				header=new BTHeaderPage(headerID);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void close()
	{
		try{
		SystemDefs.JavabaseBM.unpinPage(headerID, true);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	 public BTFileScan new_scan(KeyClass lo_key,
             KeyClass hi_key)
	 {
		 BTFileScan scan=new BTFileScan();
		 scan.setLow_key(lo_key);
		 scan.setHigh_key(hi_key);
		 
		 return scan;
	 }
	 
	 /**
	  * 
	  * Left for Mahmoud to implement
	  * 
	  */
	 
	 public BTLeafPage Search(KeyClass key)
	 {
		 try {
			return new BTLeafPage(0);
		} catch (ConstructPageException e) {
			e.printStackTrace();
			return null;
		}
	 }
	
	 public boolean Delete(KeyClass key,
             RID rid) throws DeleteRecException
	 {
		 KeyDataEntry kde=new KeyDataEntry(key,rid);
		 BTLeafPage leafPage=Search(key);
		 try{
		 return leafPage.delEntry(kde);
		 }catch(Exception e)
		 {
			throw new DeleteRecException(e,"BtreeFile.Delete(): delete failed");
		 }
	 }
	 
}
